<template>
    <v-dialog :model-value="visible" @update:model-value="$emit('update:visible', $event)" max-width="1000px" persistent
        scrollable>
        <v-card class="broker-record-card">
            <v-card-title class="pa-4 bg-primary d-flex justify-space-between">
                <div class="d-flex align-center text-white">
                    <v-icon size="32" class="mr-3">mdi-history</v-icon>
                    <div>
                        <h3 class="text-h5 font-weight-bold">操作记录</h3>
                        <!-- <div class="text-body-2 opacity-90">{{ customerRelationData.customer.name ||
                            customerRelationData.customer.name ||
                            '未知客户' }}</div> -->
                    </div>
                </div>
                <v-spacer></v-spacer>
                <v-btn icon variant="text" @click="closeDialog" class="text-white rounded-circle">
                    <v-icon>mdi-close</v-icon>
                </v-btn>
            </v-card-title>

            <v-card-text class="pa-0">
                <v-container fluid class="py-4">
                    <!-- 记录统计 -->
                    <v-row class="mb-4" no-gutters>
                        <v-col class="px-1 pa-4">
                            <!-- 全部记录按钮 -->


                            <div class="d-flex gap-2 stat-container pa-4">
                                <v-card v-for="config in statCardConfigs" :key="config.key" variant="outlined"
                                    class="flex-1 pa-3 elevation-10 stat-card"
                                    :class="{ 'stat-card-active': config.active }"
                                    @click="selectRecordType(config.key)">
                                    <div class="d-flex align-center justify-center">
                                        <div class="stat-icon-wrapper" :class="`stat-icon-${config.color}`">
                                            <v-icon size="20" color="white">{{ config.icon }}</v-icon>
                                        </div>
                                        <div class="text-center ml-2">
                                            <div class="text-h6 font-weight-bold">{{ config.count }}</div>
                                            <div class="text-caption text-grey">{{ config.title }}</div>
                                        </div>
                                    </div>
                                </v-card>
                            </div>
                        </v-col>
                    </v-row>

                    <div class="d-flex gap-2">
                        <div class="flex-1" style="flex: 1;">
                            <!-- 记录列表 -->
                            <v-row>
                                <v-col cols="12">
                                    <v-card variant="outlined">
                                        <v-card-title
                                            class="py-3 text-primary px-4 bg-grey-lighten-4 d-flex justify-space-between">
                                            <v-icon class="mr-2">mdi-format-list-bulleted</v-icon>
                                            详细记录
                                            <v-spacer></v-spacer>
                                            <v-btn size="small" variant="outlined" @click="refreshRecords">
                                                <v-icon start size="16">mdi-refresh</v-icon>
                                                刷新
                                            </v-btn>
                                        </v-card-title>

                                        <v-card-text class="pa-0" >
                                            <!-- 加载状态 -->
                                            <div v-if="loading" class="text-center py-8">
                                                <v-progress-circular indeterminate
                                                    color="primary"></v-progress-circular>
                                                <!-- <div class="mt-2 text-body-2">正在加载记录...</div> -->
                                            </div>

                                            <!-- 记录时间线 - 添加滚动容器 -->
                                            <div v-else-if="filteredRecords.length > 0"
                                                class="records-scroll-container" style="height: 100%;">
                                                <v-timeline side="end" class="pa-4">
                                                    <v-timeline-item v-for="(record, index) in filteredRecords"
                                                        :key="index" :dot-color="getRecordColor(record.type)"
                                                        size="small">
                                                        <template v-slot:icon>
                                                            <v-icon :icon="getRecordIcon(record.type)"
                                                                size="16"></v-icon>
                                                        </template>

                                                        <v-card variant="outlined" class="record-item elevation-10">
                                                            <v-card-text class="pa-3">
                                                                <div
                                                                    class="d-flex justify-space-between align-start mb-2">
                                                                    <div class="record-content-left">
                                                                        <v-chip :color="getRecordColor(record.type)"
                                                                            size="small" class="mb-2">
                                                                            {{ getRecordTypeText(record.type) }}
                                                                        </v-chip>

                                                                    </div>
                                                                    <div
                                                                        class="text-caption text-grey text-right record-meta">
                                                                        <div class="record-time">{{
                                                                            formatDateTime(record.createTime) }}</div>
                                                                        <div class="record-createBy">{{ record.createBy
                                                                        }}
                                                                        </div>
                                                                    </div>
                                                                </div>

                                                                <div v-if="record.description"
                                                                    class="text-body-2 text-grey-darken-1 mb-2 record-description details-section elevation-10">
                                                                    {{ record.description }}
                                                                </div>



                                                                <!-- 详细信息 -->
                                                                <div v-if="record.details && record.type !== '4'"
                                                                    class="details-section elevation-10">
                                                                    <div class="details-content">

                                                                        <div class="detail-row"
                                                                            v-if="record.communicationType">
                                                                            <span class="detail-label">沟通方式:</span>
                                                                            <span class="detail-value">
                                                                                {{communicationTypeOptions.find(item =>
                                                                                    item.dictValue
                                                                                    ===
                                                                                    record.communicationType)?.dictName}}</span>
                                                                        </div>
                                                                        <div v-if="record.duration" class="detail-row">
                                                                            <span class="detail-label">沟通时长:</span>
                                                                            <span class="detail-value">
                                                                                {{ record.duration }}分钟
                                                                            </span>
                                                                        </div>
                                                                        <div v-if="record.communicationTime"
                                                                            class="detail-row">
                                                                            <span class="detail-label">沟通时间:</span>
                                                                            <span class="detail-value">
                                                                                {{ record.communicationTime }}</span>
                                                                        </div>
                                                                        <div v-for="(detail, key) in JSON.parse(record.details)"
                                                                            :key="key" class="detail-row">
                                                                            <span class="detail-label">{{ key }}:</span>
                                                                            <span class="detail-value">{{ detail
                                                                            }}</span>
                                                                        </div>
                                                                        <div class="detail-row"
                                                                            v-if="record.reminderTime">
                                                                            <span class="detail-label">提醒时间:</span>
                                                                            <span class="detail-value">
                                                                                {{ record.reminderTime }}</span>
                                                                        </div>
                                                                        <div class="detail-row"
                                                                            v-if="record.assignedTo">

                                                                            <span class="detail-label">提醒人:</span>
                                                                            <span class="detail-value">
                                                                                {{ record.assignedTo }}</span>
                                                                        </div>
                                                                    </div>
                                                                </div>

                                                                <!-- 附件 -->
                                                                <div v-if="record.attachments && record.attachments.length > 0"
                                                                    class="mt-2">
                                                                    <div class="text-caption text-grey mb-1">附件:</div>
                                                                    <v-chip-group>
                                                                        <v-chip
                                                                            v-for="(attachment, idx) in record.attachments"
                                                                            :key="idx" size="small" variant="outlined"
                                                                            prepend-icon="mdi-paperclip"
                                                                            @click="downloadAttachment(attachment)">
                                                                            {{ attachment.name }}
                                                                        </v-chip>
                                                                    </v-chip-group>
                                                                </div>
                                                            </v-card-text>
                                                        </v-card>
                                                    </v-timeline-item>
                                                </v-timeline>
                                            </div>

                                            <!-- 无记录 -->
                                            <div v-else class="text-center py-8" style="height: 100%;">
                                                <v-icon size="64" class="text-grey" style="color: #7C8FAC;">
                                                    mdi-database-off</v-icon>
                                                <div class="text-h6  text-grey mt-2">暂无记录</div>
                                                <div class="text-body-2 text-grey">当前筛选条件下没有找到相关记录</div>
                                            </div>
                                        </v-card-text>

                                        <!-- 分页 -->
                                        <v-card-actions v-if="totalRecords > pageSize" class="justify-center pa-4">
                                            <v-pagination v-model="currentPage"
                                                :length="Math.ceil(totalRecords / pageSize)" :total-visible="7"
                                                @update:model-value="loadRecords"></v-pagination>
                                        </v-card-actions>
                                    </v-card>
                                </v-col>
                            </v-row>
                        </div>
                        <div class=" rounded-lg elevation-10 pa-2 broker" style="flex: 1;">
                            <!-- 创建记录的表单 -->
                            <v-card class="record-form-card w-100" variant="outlined">
                                <!-- <v-card-title class="py-3 px-4  text-primary d-flex align-center">
                                    <v-icon class="mr-2">mdi-plus</v-icon>
                                    添加记录
                                </v-card-title> -->

                                <v-card-text class="pa-4 form-scroll-container">
                                    <v-form ref="recordFormRef" v-model="recordFormValid">
                                        <!-- 记录类型选择 -->
                                        <div class="mb-6">
                                            <!-- <v-label class="text-body-2 text-medium-emphasis mb-2 d-block">
                                                <v-icon class="mr-1" size="16">mdi-format-list-bulleted-type</v-icon>
                                                记录类型
                                            </v-label> -->
                                            <div class="d-flex gap-2 record-type-buttons">
                                                <v-btn v-for="type in userAddableRecordTypes" :key="type.dictValue"
                                                    :variant="newRecord.type === type.dictValue ? 'elevated' : 'outlined'"
                                                    :color="newRecord.type === type.dictValue ? 'primary' : 'primary'"
                                                    class="flex-1" size="large"
                                                    @click="newRecord.type = type.dictValue">
                                                    <v-icon start>{{ getRecordIcon(type.dictValue) }}</v-icon>
                                                    {{ type.dictName }}
                                                </v-btn>
                                            </div>
                                        </div>
                                        <!-- 状态变更记录专用字段 -->
                                        <template v-if="formContent.showCustomerStatus" class="">
                                            <v-row>
                                                <v-col cols="12" md="12">
                                                 原状态:  <v-chip  :color="getCustomerStatusColor(customerRelationData.status)"  size="small" variant="outlined">
                                                        {{ getCustomerStatusLabel(customerRelationData.status) }}
                                                    </v-chip>
                                                </v-col>
                                                <v-col cols="12" md="12">
                                                    <!-- 单选 -->
                                                    新状态: 
                                                    <v-radio-group v-model="newRecord.details" inline   
                                                        hide-details="auto" variant="outlined"
                                                         prepend-inner-icon="mdi-swap-horizontal" class="">
                                                        <v-radio 
                                                            v-for="status in customerStatusOptions" 
                                                            :key="status.statusCode"
                                                            :disabled="status.isSystem==1"
                                                            :label="status.statusName" 
                                                            :value="status.statusCode">
                                                        </v-radio>
                                                    </v-radio-group>
                                                   
                                                   <!-- 新状态：{{ getCustomerStatusLabel(newRecord.newStatus) }} -->
                                                </v-col>
                                            </v-row>
                                        </template>
                                        <!-- 沟通记录专用字段 -->
                                        <template v-if="formContent.showCommunicationFields" class="">
                                            <v-row>
                                                <v-col cols="12" md="6">
                                                    <v-select v-model="newRecord.communicationType" label="沟通方式"
                                                        :items="communicationTypeOptions" item-title="dictName"
                                                        hide-details="auto" item-value="dictValue" variant="outlined"
                                                        density="comfortable" prepend-inner-icon="mdi-phone" class="" />
                                                </v-col>
                                                <v-col cols="12" md="6">
                                                    <v-text-field v-model="newRecord.duration" label="沟通时长(分钟)"
                                                        variant="outlined" density="comfortable" hide-details="auto"
                                                        prepend-inner-icon="mdi-clock-outline" placeholder="例如：10"
                                                        class="" />
                                                </v-col>
                                            </v-row>
                                        </template>


                                        <!-- 描述内容 -->
                                        <v-textarea v-model="newRecord.description"
                                            :label="formContent.descriptionLabel" variant="outlined"
                                            density="comfortable" :rules="[formContent.descriptionRule]"
                                            prepend-inner-icon="mdi-text" hide-details="auto"
                                            :placeholder="formContent.descriptionPlaceholder" rows="4"
                                            class="mb-3 mt-3" />


                                        <!-- 提醒字段 - 沟通记录和其他记录显示 -->
                                        <template v-if="formContent.showReminderFields">
                                            <v-row>
                                                <v-col cols="12" md="6">
                                                    <v-text-field v-model="newRecord.reminderTime" label="提醒时间"
                                                        type="datetime-local" variant="outlined" density="comfortable"
                                                        hide-details="auto" prepend-inner-icon="mdi-bell-outline"
                                                        placeholder="设置提醒时间（可选）" class="mb-3" />
                                                </v-col>
                                                <v-col cols="12" md="6">
                                                    <SelectUser v-model="selectedAssignedUser" label="提醒人"
                                                        hide-details="auto" placeholder="选择提醒人（可选）" variant="outlined"
                                                        density="comfortable"
                                                        prepend-inner-icon="mdi-account-arrow-right"
                                                        @user-selected="handleAssignedUserSelect" class="mb-3" />
                                                </v-col>
                                            </v-row>
                                        </template>

                                        <!-- 附件上传 - 仅非沟通记录显示 -->
                                        <div v-if="formContent.showAttachments" class="mb-3">
                                            <v-label class="text-body-2 text-medium-emphasis mb-2 d-block">
                                                <v-icon class="mr-1" size="16">mdi-paperclip</v-icon>
                                                附件 (可选)
                                            </v-label>
                                            <v-file-input v-model="uploadFiles" label="选择文件" variant="outlined"
                                                density="comfortable" multiple prepend-inner-icon="mdi-file-upload"
                                                accept="image/*,.pdf,.doc,.docx,.xls,.xlsx"
                                                placeholder="支持图片、PDF、Word、Excel等格式" show-size class="mb-2" />
                                            <div v-if="newRecord.attachments && newRecord.attachments.length > 0"
                                                class="mt-2">
                                                <v-chip-group>
                                                    <v-chip v-for="(file, index) in newRecord.attachments" :key="index"
                                                        size="small" closable @click:close="removeAttachment(index)"
                                                        prepend-icon="mdi-file">
                                                        {{ file.name }}
                                                    </v-chip>
                                                </v-chip-group>
                                            </div>
                                        </div>

                                        <!-- 操作按钮 -->
                                        <div class="d-flex gap-2 justify-end">

                                            <v-btn @click="saveRecord" color="primary" variant="elevated"
                                                :loading="saving">
                                                <v-icon start size="16">mdi-content-save</v-icon>
                                                保存记录
                                            </v-btn>
                                        </div>
                                    </v-form>
                                </v-card-text>
                            </v-card>
                        </div>
                    </div>
                </v-container>
            </v-card-text>

            <v-card-actions class="px-6 py-4 bg-grey-lighten-4">
                <!-- <v-btn @click="exportRecords" color="success" variant="outlined" class="mr-2">
                    <v-icon start>mdi-download</v-icon>
                    导出记录
                </v-btn> -->
                <v-spacer></v-spacer>
                <v-btn @click="closeDialog" color="primary" variant="elevated">
                    关闭
                </v-btn>
            </v-card-actions>
        </v-card>
    </v-dialog>
</template>

<script setup lang="ts">
import { getStorage, setStorage, removeStorage } from '@/utils/storage'

import { ref, reactive, computed, watch, onMounted } from 'vue';
import type { CustomerStudentRelationModel } from '@/api/customer/customerrelation/CustomerStudentRelationManagementApi';
import { useDict } from '@/composables/useDict';
import {
    getList,
    doInsert,
    doUpdate,
    doDelete
} from '@/api/customer/record/CustmoerRecordManagementApi';
import type {
    CustomerRecordModel,
    CustomerRecordQueryParams
} from '@/api/customer/record/CustmoerRecordManagementApi';
import type { DictItem } from '@/utils/dict';
import SelectUser from '@/components/SelectUser.vue';
import type { UserInfo } from '@/components/SelectUser.vue';
import { useUserStore } from '@/store/user';
import type { TenantCustomerStatusModel } from '@/api/tenant/customerstatus/TenantCustomerStatusManagementApi';

const userStore = useUserStore();
const { getDictNameByValueSync, getDictList } = useDict();
import { useMessage } from '@/composables/useMessage';

// 使用更新后的 useMessage，现在可以直接使用 showSuccess 和 showError
const { showSuccess, showError } = useMessage();

// 记录类型定义 - 使用API中的类型并扩展
interface ExtendedCustomerRecord extends Omit<CustomerRecordModel, 'attachments'> {
    attachments?: Array<{
        name: string;
        url: string;
        size: number;
    }>;
}

// Props
interface Props {
    visible: boolean;
    customerRelationData: CustomerStudentRelationModel;
    selectedRecordType: number;
}

const props = withDefaults(defineProps<Props>(), {
    visible: false,
    customerRelationData: () => ({} as CustomerStudentRelationModel),
    selectedRecordType: () => (0)
});

// Emits
const emit = defineEmits<{
    'update:visible': [value: boolean];
}>();

// 组件引用
const recordFormRef = ref();

// 响应式数据
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(1000);
const totalRecords = ref(0);
const records = ref<ExtendedCustomerRecord[]>([]);
const recordFormValid = ref(false);
const saving = ref(false);
const uploadFiles = ref<File[]>([]);

// 本地状态 - 记录类型选择
const localSelectedRecordType = ref(props.selectedRecordType);


// 新记录表单数据 - 使用API类型
const newRecord = ref<Partial<ExtendedCustomerRecord>>({
    type: '1', // 默认为沟通记录，使用字符串类型
    description: '',
    createBy: '', // 当前用户
    createTime: '',
    communicationType: '1', // 默认为电话
    duration: 10,
    customerId: props.customerRelationData?.id, // 将通过computed自动设置
    reminderTime: '',
    assignedTo: '',
    attachments: []
});

// 选项数据
let communicationTypeOptions = ref<DictItem[]>([]);
let recordTypeOptions = ref<DictItem[]>([]);

// 记录统计
const recordStats = reactive({
    operations: 0,
    statusChanges: 0,
    documents: 0,
    communications: 0
});

const customerStatusOptions = ref<TenantCustomerStatusModel[]>(
    getStorage('allCustomerStatus') as TenantCustomerStatusModel[]
);



// 计算属性
const filteredRecords = computed(() => {
    if (localSelectedRecordType.value === 0) {
        return records.value;
    }
    return records.value.filter(record => record.type?.toString() == localSelectedRecordType.value.toString());
});

// 计算属性 - 动态统计卡片配置
const statCardConfigs = computed(() => {
    return [
        {
            key: '0',
            title: '全部记录',
            count: records.value.length,
            icon: 'mdi-format-list-bulleted',
            color: 'primary',
            active: localSelectedRecordType.value === 0
        },
        ...recordTypeOptions.value.map(type => ({
            key: type.dictValue,
            title: type.dictName,
            count: getCountByType(type.dictValue),
            icon: getRecordIcon(type.dictValue),
            color: getRecordColor(type.dictValue),
            active: localSelectedRecordType.value?.toString() === type.dictValue
        }))
    ];
});

// 计算属性 - 用户可添加的记录类型（排除系统自动生成的类型）
const userAddableRecordTypes = computed(() => {
    // 用户可手动添加的记录类型：
    // - 沟通记录(1)：用户主动记录与经纪人的沟通情况
    // - 其他记录(4)：用户上传相关文档和资料
    // 
    // 系统自动生成的记录类型：
    // - 状态变更(2)：当经纪人状态发生变化时由后端自动创建
    // - 操作记录(3)：当进行各种操作时由后端自动创建
    return recordTypeOptions.value.filter(type =>
        type.dictValue === '1' || type.dictValue === '4' || type.dictValue === '2' 
    );
});

// 根据类型获取统计数量
function getCountByType(type: string): number {
    switch (type) {
        case '1': return recordStats.communications;
        case '2': return recordStats.statusChanges;
        case '3': return recordStats.operations;
        case '4': return recordStats.documents;
        default: return 0;
    }
}

// 计算属性 - 表单动态内容
const formContent = computed(() => {
    const currentType = recordTypeOptions.value.find(type => type.dictValue === newRecord.value.type);
    const typeName = currentType?.dictLabel || '记录';

    const ruleMessage = newRecord.value.type === '1' ? '请输入沟通内容' :
        newRecord.value.type === '4' ? '记录内容' :
            `请输入${typeName}描述`;

    return {
        descriptionLabel: newRecord.value.type === '1' ? '沟通内容' :
            newRecord.value.type === '4' ? '记录内容' :
                `${typeName}描述`,
        descriptionPlaceholder: newRecord.value.type === '1' ? '请详细描述沟通内容...' :
            newRecord.value.type === '4' ? '请描述文档内容和用途...' :
                `请详细描述${typeName}内容...`,
        showCustomerStatus: newRecord.value.type === '2' ,
        descriptionRule: (v: any) => !!v || ruleMessage,
        showCommunicationFields: newRecord.value.type === '1',
        showReminderFields: newRecord.value.type === '1' || newRecord.value.type === '4',
        showAttachments: newRecord.value.type !== '1' &&newRecord.value.type !== '2'
    };
});

// 监听记录类型变化
watch(() => props.selectedRecordType, (newValue) => {
    localSelectedRecordType.value = newValue;
    currentPage.value = 1;
    loadRecords();
}, { immediate: true });

// 监听对话框显示状态
watch(() => props.visible, (visible) => {
    if (visible) {
        // 确保字典数据已加载
        if (communicationTypeOptions.value.length === 0) {
            initDict();
        }
        loadRecords();
    }
});


// 获取客户状态名称
function getCustomerStatusLabel(value: any): string {
    const customerStatus = getStorage('allCustomerStatus') as TenantCustomerStatusModel[];
    const item = customerStatus.find((item) => item.statusCode == value);
    return item?.statusName || '未知';
}

function getCustomerStatusColor(value: any): string {
    const customerStatus = getStorage('allCustomerStatus') as TenantCustomerStatusModel[];
    const item = customerStatus.find((item) => item.statusCode == value);
    return item?.statusColor || 'primary';
}

// 获取记录颜色
function getRecordColor(type: string | number | undefined): string {
    if (!type) return 'grey';
    const typeStr = type.toString();
    const colors: Record<string, string> = {
        '1': 'primary',
        '2': 'success',
        '3': 'info',
        '4': 'warning',
    };
    return colors[typeStr] || 'grey';
}

// 获取记录图标
function getRecordIcon(type: string | number | undefined): string {
    if (!type) return 'mdi-circle';
    const typeStr = type.toString();
    const icons: Record<string, string> = {
        '1': 'mdi-message-text',
        '2': 'mdi-swap-horizontal',
        '3': 'mdi-account-edit',
        '4': 'mdi-file-document',
    };
    return icons[typeStr] || 'mdi-circle';
}

// 获取记录类型文本
function getRecordTypeText(type: string | number | undefined): string {
    if (!type) return '';
    const dictName = getDictNameByValueSync('broker_record_type', type.toString());
    return dictName || '';
}

// 格式化日期时间
function formatDateTime(datetime: string | undefined): string {
    if (!datetime) return '-';
    try {
        return new Date(datetime).toLocaleString('zh-CN');
    } catch {
        return '-';
    }
}

// 加载记录数据
async function loadRecords() {
    loading.value = true;
    try {
        const queryParams: CustomerRecordQueryParams = {
            pageNo: currentPage.value,
            pageSize: pageSize.value,
            customerId_EQ: props.customerRelationData.id,
            orderBy: 'createTime',
            sortOrder_ORDER: 'DESC'
        };

        // // 根据选择的记录类型添加过滤条件
        // console.log(localSelectedRecordType.value);
        // if (localSelectedRecordType.value !== 0) {
        //     queryParams.type_EQ = localSelectedRecordType.value.toString();
        // }
        // console.log(queryParams.type_EQ);

        const { data, code, msg } = await getList(queryParams);
        if (code === 0) {

            records.value = data.rows.map((record: any) => ({
                ...record,
                // 解析附件JSON字符串
                attachments: record.attachments ? JSON.parse(record.attachments) : [],
                assignedTo: userStore.getUserNameByIdSync(record.assignedTo || ''),
                createBy: userStore.getUserNameByIdSync(record.createBy || '')
            }));
            totalRecords.value = data.total;
            // 计算统计数据
            await calculateStatistics();
        } else {
            console.error('加载记录失败:', msg);
            records.value = [];
            totalRecords.value = 0;
            resetStatistics();
        }
    } catch (error) {
        console.error('加载记录失败:', error);
        records.value = [];
        totalRecords.value = 0;
        resetStatistics();
    } finally {
        loading.value = false;
    }
}

// 计算统计数据
async function calculateStatistics() {
    // 重置统计数据
    resetStatistics();

    try {
        // 获取该经纪人的所有记录用于统计（不分页，不过滤类型）
        records.value.forEach((record: any) => {
            if (record?.type) {
                switch (record?.type) {
                    case '1':
                        recordStats.communications++;
                        break;
                    case '2':
                        recordStats.statusChanges++;
                        break;
                    case '3':
                        recordStats.operations++;
                        break;
                    case '4':
                        recordStats.documents++;
                        break;
                }
            }
        });
    } catch (error) {
        console.error('加载统计数据失败:', error);
    }
}

// 重置统计数据
function resetStatistics() {
    recordStats.operations = 0;
    recordStats.statusChanges = 0;
    recordStats.documents = 0;
    recordStats.communications = 0;
}

// 刷新记录
function refreshRecords() {
    loadRecords();
}

// 下载附件
function downloadAttachment(attachment: any) {
    console.log('下载附件:', attachment);
    // 创建临时链接下载文件
    const link = document.createElement('a');
    link.href = attachment.url;
    link.download = attachment.name;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

// 导出记录
function exportRecords() {
    console.log('导出记录');
    // 实现导出逻辑
}

// 关闭对话框
function closeDialog() {
    emit('update:visible', false);
}

async function initDict() {
    let data = await getDictList("communication_type") || [];

    communicationTypeOptions.value = await getDictList("communication_type") || [];
    recordTypeOptions.value = await getDictList("broker_record_type") || [];
    console.log('沟通方式字典数据:', communicationTypeOptions.value);
    console.log('记录类型字典数据:', recordTypeOptions.value);

    // 加载客户状态数据
    await userStore.loadAllCustomerStatus();
    customerStatusOptions.value = userStore.allCustomerStatus;

    // 设置默认记录类型为第一个用户可添加的类型
    if (userAddableRecordTypes.value.length > 0 && !newRecord.value.type) {
        newRecord.value.type = userAddableRecordTypes.value[0].dictValue;
    }
}

// 组件挂载时加载数据
onMounted(() => {
    // 首先初始化字典数据
    initDict();

    if (props.visible) {
        loadRecords();
    }
});

// 保存记录
async function saveRecord() {
    if (!recordFormRef.value) return;

    const { valid } = await recordFormRef.value.validate();
    if (!valid) return;

    // 验证记录类型是否为用户可添加的类型
    const isValidType = userAddableRecordTypes.value.some(type => type.dictValue === newRecord.value.type);
    if (!isValidType) {
        console.error('无效的记录类型，只能添加沟通记录和其他记录');
        return;
    }

    //如果是其他记录 就移除沟通方式与沟通时长
    if (newRecord.value.type === '4') {
        newRecord.value.communicationType = undefined;
        newRecord.value.duration = undefined;
    }


    // return;
    saving.value = true;
    try {
        // 处理附件上传 - 只有非沟通记录才有附件
        if (newRecord.value.type !== '1' && uploadFiles.value && uploadFiles.value.length > 0) {
            const attachments = [];
            for (const file of uploadFiles.value) {
                // 这里应该调用文件上传API
                // const uploadResult = await uploadFile(file);
                attachments.push({
                    name: file.name,
                    url: URL.createObjectURL(file), // 临时URL，实际应该是上传后的URL
                    size: file.size
                });
            }
            newRecord.value.attachments = attachments;
        }

        // 设置操作者和创建时间
        // newRecord.createBy = 'Current User'; // 实际应该从用户信息中获取
        newRecord.value.createTime = new Date().toISOString();
        newRecord.value.customerId = props.customerRelationData.customerId;

        // 构建详细信息
        const details: Record<string, any> = {};
        if (newRecord.value.type === '1') {
            // details['沟通方式'] = newRecord.communicationType;
            // details['沟通时长'] = newRecord.duration;
            // details['联系人'] = props.brokerData.preferredName || props.brokerData.legalName;
            // 只有设置了提醒时间才添加提醒相关信息
            // if (newRecord.reminderTime) {
            //     details['提醒时间'] = newRecord.reminderTime;
            //     if (newRecord.assignedTo) {
            //         details['提醒人'] = newRecord.assignedTo;
            //     }
            // }
        } else if (newRecord.value.type === '4') {
            // 其他记录的提醒信息
            // if (newRecord.reminderTime) {
            //     details['提醒时间'] = newRecord.reminderTime;
            //     if (newRecord.assignedTo) {
            //         details['提醒人'] = newRecord.assignedTo;
            //     }
            // }
        }

        // 准备API请求数据
        const recordData: Partial<CustomerRecordModel> = {
            type: newRecord.value.type,
            description: newRecord.value.description,
            details: JSON.stringify(details),
            attachments: newRecord.value.attachments ? JSON.stringify(newRecord.value.attachments) : undefined,
            communicationType: newRecord.value.communicationType,
            duration: newRecord.value.duration,
            customerId: props.customerRelationData.id,
            reminderTime: newRecord.value.reminderTime,
            assignedTo: newRecord.value.assignedTo,
            createBy: newRecord.value.createBy
        };

        // 调用API保存记录
        const { msg, code } = await doInsert(recordData);
        if (code === 0) {
            showSuccess('保存成功');
            // 重新加载数据
            await loadRecords();
            // 重置表单
            resetForm();
        }
    } catch (error) {
        console.error('保存记录失败:', error);
    } finally {
        saving.value = false;
    }
}

// 重置表单
function resetForm() {
    if (recordFormRef.value) {
        recordFormRef.value.reset();
    }

    // 重置表单数据
    Object.assign(newRecord.value, {
        type: userAddableRecordTypes.value.length > 0 ? userAddableRecordTypes.value[0].dictValue : '1', // 默认为第一个可添加的记录类型
        description: '',
        createBy: '', // 当前用户
        createTime: '',
        communicationType: '1', // 默认为第一个沟通方式
        duration: 10,
        customerId: props.customerRelationData.id, // 将通过computed自动设置
        reminderTime: '',
        assignedTo: '',
        attachments: []
    });

    // 重置选中的用户
    selectedAssignedUser.value = null;
    uploadFiles.value = [];
}

// 移除附件
function removeAttachment(index: number) {
    if (newRecord.value.attachments) {
        newRecord.value.attachments.splice(index, 1);
    }
}

// 选择记录类型
function selectRecordType(type: string) {
    localSelectedRecordType.value = Number(type);
    currentPage.value = 1;
    // loadRecords();
}

// 获取联系人显示文本
function getContactPersonDisplay(): string {
    return props.customerRelationData.customer.name || props.customerRelationData.customer.name || '未知客户';
}

// 新增的变量和方法
const selectedAssignedUser = ref<UserInfo | null>(null);

function handleAssignedUserSelect(user: UserInfo | null) {
    if (user) {
        newRecord.value.assignedTo = user.id;
        selectedAssignedUser.value = user;
    } else {
        newRecord.value.assignedTo = '';
        selectedAssignedUser.value = null;
    }
}

// const formattedReminderTime = computed({
//     get: () => {
//         if (!newRecord.value.reminderTime) return ''
//         const date = new Date(newRecord.value.reminderTime)
//         // 格式化为 YYYY-MM-DDTHH:mm 格式（datetime-local 输入框需要的格式）
//         return date.toISOString().slice(0, 16)
//     },
//     set: (value) => {
//         if (!value) {
//             newRecord.value.reminderTime = ''
//             return
//         }
//         // 将输入的日期时间字符串转换为 ISO 格式
//         newRecord.value.reminderTime = new Date(value).toISOString()
//     }
// })
</script>

<style scoped>
/* 统计卡片容器 */
.stat-container {
    flex-wrap: nowrap;
    /* 禁止换行 */
    overflow-x: auto;
    /* 小屏幕时允许水平滚动 */
    min-height: 80px;
}

/* 统计图标包装器 */
.stat-icon-wrapper {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    transition: all 0.3s ease;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stat-icon-primary {
    background: linear-gradient(135deg, #2196f3 0%, #1976d2 100%);
}

.stat-icon-success {
    background: linear-gradient(135deg, #4caf50 0%, #388e3c 100%);
}

.stat-icon-info {
    background: linear-gradient(135deg, #00bcd4 0%, #0097a7 100%);
}

.stat-icon-warning {
    background: linear-gradient(135deg, #ff9800 0%, #f57c00 100%);
}

.stat-icon-error {
    background: linear-gradient(135deg, #f44336 0%, #d32f2f 100%);
}

.stat-card:hover .stat-icon-wrapper {
    transform: scale(1.1);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

/* 统计卡片样式 */
.stat-card {
    border-radius: 12px;
    transition: all 0.3s ease;
    border: 1px solid #e0e0e0;
    min-height: 80px;
    min-width: 140px;
    /* 设置最小宽度防止过度压缩 */
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    /* 添加手指指针 */
}

.stat-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15) !important;
    border-color: rgba(25, 118, 210, 0.3);
}

/* 选中状态样式 */
.stat-card-active {
    border-color: #1976d2 !important;
    background-color: rgba(25, 118, 210, 0.05) !important;
    transform: translateY(-1px);
    box-shadow: 0 6px 20px rgba(25, 118, 210, 0.2) !important;
}

.stat-card-active:hover {
    transform: translateY(-3px);
    box-shadow: 0 10px 30px rgba(25, 118, 210, 0.25) !important;
}

.stat-card .text-h6 {
    line-height: 1.2;
    margin-bottom: 2px;
    font-size: 1rem !important;
    white-space: nowrap;
    /* 防止数字换行 */
}

.stat-card .text-caption {
    line-height: 1.1;
    font-size: 0.7rem;
    opacity: 0.7;
    white-space: nowrap;
    /* 防止标签换行 */
}

.broker-record-card {
    max-height: 90vh;
    overflow-y: auto;
}

.record-item {
    margin-bottom: 8px;
    transition: all 0.2s ease;
    width: 300px;
    /* 限制最大宽度 */
    word-wrap: break-word;
    /* 自动换行 */
    word-break: break-all;
    /* 强制换行 */
}

.record-item:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 记录卡片内容样式优化 */
.record-item .v-card-text {
    line-height: 1.4;
    /* 紧凑行高 */
    padding: 12px 16px !important;
    /* 减小内边距 */
}

/* 记录左侧内容区域 */
.record-content-left {
    flex: 1;
    min-width: 0;
    /* 允许收缩 */
}

/* 记录标题样式 */
.record-title {
    font-size: 0.95rem !important;
    line-height: 1.3 !important;
    margin-bottom: 4px;
    word-wrap: break-word;
    overflow-wrap: break-word;
    white-space: normal;
}

/* 记录元信息样式 */
.record-meta {
    flex-shrink: 0;
    min-width: 120px;
    max-width: 150px;
}

.record-time,
.record-createBy {
    font-size: 0.75rem;
    line-height: 1.2;
    margin-bottom: 2px;
    word-wrap: break-word;
}

/* 记录描述样式 */
.record-description {
    font-size: 0.875rem !important;
    line-height: 1.4 !important;
    margin-bottom: 8px !important;
    padding: 0;
    word-wrap: break-word;
    overflow-wrap: break-word;
}

/* 详细信息区域优化 */
.details-section {
    background: rgba(0, 0, 0, 0.02);
    border-radius: 6px;
    padding: 8px;
    margin-top: 8px;
    border: 1px solid #f0f0f0;
}

.record-item .text-body-1 {
    line-height: 1.3;
    word-wrap: break-word;
    overflow-wrap: break-word;
}

.record-item .text-body-2 {
    line-height: 1.3;
    word-wrap: break-word;
    overflow-wrap: break-word;
}

.record-item .text-caption {
    line-height: 1.2;
    word-wrap: break-word;
}

/* 记录标题样式优化 */
.record-item .font-weight-medium {
    white-space: normal;
    word-wrap: break-word;
    overflow-wrap: break-word;
    hyphens: auto;
}

/* 描述文本样式优化 */
.record-item .text-grey-darken-1 {
    white-space: normal;
    word-wrap: break-word;
    overflow-wrap: break-word;
    margin-bottom: 12px !important;
}

/* 详细信息区域样式 */
.details-content {
    display: grid;
    gap: 6px;
    /* 减小间距让内容更紧凑 */
}

.detail-row {
    display: flex;
    padding: 3px 0;
    /* 减小内边距 */
    border-bottom: 1px solid #f0f0f0;
    /* 两边对齐 */
    align-items: justify;
    /* 顶部对齐 */
}

.detail-label {
    font-weight: 500;
    min-width: 100px;
    /* 减小最小宽度 */
    max-width: 120px;
    /* 限制最大宽度 */
    color: #666;
    font-size: 0.875rem;
    /* 稍微减小字体 */
    line-height: 1.3;
    flex-shrink: 0;
    /* 防止收缩 */
}

.detail-value {
    color: #333;
    font-weight: 500;
    flex: 1;
    margin-left: 8px;
    /* 减小左边距 */
    font-size: 0.875rem;
    /* 稍微减小字体 */
    line-height: 1.3;
    word-wrap: break-word;
    overflow-wrap: break-word;
    white-space: normal;
}

/* 附件区域样式优化 */
.record-item .v-chip-group {
    margin-top: 4px;
}

.record-item .v-chip-group .v-chip {
    margin: 2px 4px 2px 0;
    font-size: 0.75rem;
    height: 24px;
}

/* 自定义滚动条 */
.broker-record-card::-webkit-scrollbar {
    width: 6px;
}

.broker-record-card::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
}

.broker-record-card::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
}

.broker-record-card::-webkit-scrollbar-thumb:hover {
    background: #a1a1a1;
}

/* 记录创建表单样式 */
.record-form-card {
    border-radius: 12px;
    transition: all 0.3s ease;
}

.record-form-card:hover {
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.record-form-card .v-card-title {
    /* background: linear-gradient(135deg, rgb(var(--v-theme-primary)) 0%, rgb(var(--v-theme-primary-darken-1)) 100%); */
    border-radius: 12px 12px 0 0;
}

/* 表单字段动画效果 */
:deep(.v-field) {
    transition: all 0.3s ease;
}

:deep(.v-field:hover) {
    transform: translateY(-1px);
}

:deep(.v-field--focused) {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(var(--v-theme-primary), 0.2);
}

/* 按钮样式 */
.v-btn {
    border-radius: 8px;
    font-weight: 600;
    text-transform: none;
    transition: all 0.3s ease;
}

.v-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

/* 文件上传区域样式 */
:deep(.v-file-input) {
    border: 2px dashed rgba(var(--v-theme-primary), 0.3);
    border-radius: 8px;
    transition: all 0.3s ease;
}

:deep(.v-file-input:hover) {
    border-color: rgb(var(--v-theme-primary));
    background-color: rgba(var(--v-theme-primary), 0.05);
}

/* 标签样式 */
:deep(.v-chip) {
    border-radius: 6px;
    font-weight: 500;
}

/* 滚动条样式 */
.record-form-card::-webkit-scrollbar {
    width: 4px;
}

.record-form-card::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 2px;
}

.record-form-card::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 2px;
}

.record-form-card::-webkit-scrollbar-thumb:hover {
    background: #a1a1a1;
}

/* 记录列表滚动容器 */
.records-scroll-container {
    max-height: 500px;
    overflow-y: auto;
    border-radius: 4px;
}

.records-scroll-container::-webkit-scrollbar {
    width: 6px;
}

.records-scroll-container::-webkit-scrollbar-track {
    background: #f5f5f5;
    border-radius: 3px;
}

.records-scroll-container::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
    transition: background 0.3s ease;
}

.records-scroll-container::-webkit-scrollbar-thumb:hover {
    background: #a1a1a1;
}

/* 表单滚动容器 */
.form-scroll-container {
    max-height: 500px;
    overflow-y: auto;
}

.form-scroll-container::-webkit-scrollbar {
    width: 6px;
}

.form-scroll-container::-webkit-scrollbar-track {
    background: #f5f5f5;
    border-radius: 3px;
}

.form-scroll-container::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
    transition: background 0.3s ease;
}

.form-scroll-container::-webkit-scrollbar-thumb:hover {
    background: #a1a1a1;
}

/* 移动端优化 */
@media (max-width: 768px) {
    .record-item {
        max-width: 100%;
        /* 小屏幕时使用全宽 */
    }

    .record-item .v-card-text {
        padding: 8px 12px !important;
        /* 进一步减小移动端内边距 */
    }

    .record-meta {
        min-width: 100px;
        max-width: 120px;
    }

    .record-time,
    .record-createBy {
        font-size: 0.7rem;
    }

    .detail-label {
        min-width: 80px;
        max-width: 100px;
        font-size: 0.8rem;
    }

    .detail-value {
        font-size: 0.8rem;
        margin-left: 6px;
    }

    /* 统计卡片移动端优化 */
    .stat-card {
        min-width: 120px;
        padding: 8px !important;
    }

    .stat-icon-wrapper {
        width: 36px;
        height: 36px;
    }

    .stat-icon-wrapper .v-icon {
        font-size: 18px !important;
    }

    .stat-card .text-h6 {
        font-size: 0.9rem !important;
    }

    .stat-card .text-caption {
        font-size: 0.65rem;
    }

    /* 移动端滚动容器优化 */
    .records-scroll-container {
        max-height: 400px;
    }

    .form-scroll-container {
        max-height: 400px;
    }
}

@media (max-width: 480px) {
    .record-item .d-flex.justify-space-between {
        flex-direction: column;
        gap: 8px;
    }

    .record-meta {
        align-self: flex-end;
        text-align: right;
    }

    .detail-row {
        flex-direction: column;
        gap: 2px;
        padding: 4px 0;
    }

    .detail-label {
        min-width: auto;
        max-width: none;
        margin-bottom: 2px;
    }

    .detail-value {
        margin-left: 0;
    }

    /* 极小屏幕统计卡片优化 */
    .stat-card {
        min-width: 100px;
        padding: 6px !important;
    }

    .stat-icon-wrapper {
        width: 32px;
        height: 32px;
    }

    .stat-icon-wrapper .v-icon {
        font-size: 16px !important;
    }

    .stat-card .text-h6 {
        font-size: 0.8rem !important;
    }

    .stat-card .text-caption {
        font-size: 0.6rem;
    }

    /* 极小屏幕滚动容器优化 */
    .records-scroll-container {
        max-height: 300px;
    }

    .form-scroll-container {
        max-height: 300px;
    }
}

/* 全部记录按钮样式 */
.all-records-btn {
    border-radius: 20px;
    font-weight: 600;
    text-transform: none;
    transition: all 0.3s ease;
    min-width: 120px;
}

.all-records-btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 记录类型按钮样式 */
.record-type-buttons .v-btn {
    border-radius: 8px !important;
    font-weight: 600;
    text-transform: none;
    transition: all 0.3s ease;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.record-type-buttons .v-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.record-type-buttons .v-btn--elevated {
    box-shadow: 0 4px 12px rgba(var(--v-theme-primary), 0.3) !important;
}
</style>@/api/customer/record/CustmoerRecordManagementApi@/api/customer/record/CustmoerRecordManagementApi